package top.jpower.jpower.builder.auth.granter;

import top.jpower.jpower.builder.auth.AuthUserInfo;
import top.jpower.jpower.builder.auth.TokenGranter;
import top.jpower.jpower.builder.auth.TokenParameter;
import top.jpower.jpower.cache.UserCache;
import top.jpower.jpower.dbs.entity.core.user.TbCoreUser;
import top.jpower.jpower.module.common.auth.UserInfo;
import top.jpower.jpower.module.common.utils.Fc;
import top.jpower.jpower.service.core.user.CoreUserService;
import top.jpower.jpower.utils.UserUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static top.jpower.jpower.builder.auth.granter.PasswordTokenGranter.GRANT_TYPE;


/**
 * @Author 郭丁志
 * @Description //TODO 密码登录默认实现类
 * @Date 00:50 2020-07-28
 **/
@Component(GRANT_TYPE)
@RequiredArgsConstructor
public class PasswordTokenGranter implements TokenGranter {

	public static final String GRANT_TYPE = "password";

	@Autowired(required = false)
	private AuthUserInfo authUserInfo;
	private final CoreUserService userService;

	@Override
	public UserInfo grant(TokenParameter tokenParameter) {
		String account = tokenParameter.getLoginId();
		String password = tokenParameter.getPassWord();
		String tenantCode = tokenParameter.getTenantCode();
		if (Fc.isNoneBlank(account, password)) {
			if (!Fc.isNull(authUserInfo)){
				return authUserInfo.getPasswordUserInfo(tokenParameter);
			}else {
				if (userService.validatePassword(account,password,tenantCode)){
					TbCoreUser result = UserCache.getUserByLoginId(account, tenantCode);
					return UserUtil.toUserInfo(result);
				}
			}
		}
		return null;
	}

}

